package com.wisely.springbootjpa.web;

import com.wisely.springbootjpa.domain.User;
import com.wisely.springbootjpa.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("users")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/add//{name}/{address}/{age}")
    public User addUser( @PathVariable String name,
                        @PathVariable String address,@PathVariable int age) {
        User user = new User();
        user.setName(name);
        user.setAddress(address);
        user.setAge(age);
        userService.saveUser(user);
        return user;
    }

    @RequestMapping(value = "/delete/{id}")
    public void deleteUser(@PathVariable int id) {
        userService.delete(id);
    }

    @RequestMapping(value = "/")
    public List<User> getUser() {
        return userService.findAll();
    }

    @RequestMapping(value = "/{id}")
    public User getUser(@PathVariable int id) {
        User user = userService.findOne(id);
        return user;
    }

    @RequestMapping(value = "/search/name/{name}")
    public List<User> getUserByName(@PathVariable String name) {
        List<User> users = userService.findByName(name);
        return users;
    }

    @RequestMapping(value = "/search/nameSort/{name}")
    public List<User> getUserByNameSort(@PathVariable String name) {
        List<User> users = userService.findByNameAndDesc(name);
        return users;
    }

    @RequestMapping(value = "/search/page/{name}")
    public List<User> getUserByNamePage(@PathVariable String name) {
        List<User> users = userService.findByNamePage(name);
        return users;
    }

    @RequestMapping(value = "/search/namelike/{name}")
    public List<User> getUserByNameLike(@PathVariable String name) {
        List<User> users = userService.findByNameLike("%" + name + "%");
        return users;
    }

    @RequestMapping(value = "/search10/name/{name}")
    public List<User> get10UsersByName(@PathVariable String name) {
        List<User> users = userService.find10ByName(name);
        return users;
    }

    @RequestMapping(value = "/modify/{name}/{id}")
    public void updateUser(@PathVariable String name, @PathVariable int id) {
        userService.updateUsernameById(name,id);
    }

    @RequestMapping(value = "/search/frombeijing")
    public List<User> findFromBeijing() {
        List<User> users = userService.findFromBeijing();
        return users;
    }
}
